<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Author: Andy <191142742@qq.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 从数组中取出索引项
 * @param type   $arg 参数
 * @param array  $list 数组
 * @param string $default 默认值
 * @return string
 */
function arrText($arg, $list = ['-1' => '删除', '0' => '禁用', '1' => '正常'],$default=null)
{
    if (array_key_exists($arg, $list)) {
        return $list[$arg];
    }
    return $default;
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function random_string($len = 6)
{
    $chars = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    ];
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

/**
 * 密码加密方法
 * @param string $pw 要加密的原始密码
 * @param string $authCode 加密字符串
 * @return string
 */
function password($pw, $authCode = 'Andy_zhu')
{
    if (empty($authCode)) {
        $authCode = config('database.authcode');
    }
    $result = "###" . md5(md5($authCode . $pw));
    return $result;
}

/**
 * 密码比较方法,所有涉及密码比较的地方都用这个方法
 * @param string $password 要比较的密码
 * @param string $passwordInDb 数据库保存的已经加密过的密码
 * @return boolean 密码相同，返回true
 */
function compare_password($password, $passwordInDb)
{
    if (strpos($passwordInDb, "###") === 0) {
        return cmf_password($password) == $passwordInDb;
    } else {
        return cmf_password_old($password) == $passwordInDb;
    }
}

/**
 * 文件日志
 * @param        $content 要写入的内容
 * @param string $file 日志文件,在web 入口目录
 */
function write_log($content, $file = "log.txt")
{
    file_put_contents($file, $content, FILE_APPEND);
}

/**
 * 生成用户 token
 * @param int $userId 用户 ID
 * @param string $deviceType 设备类型(mobile,android,iphone,ipad,web,pc,mac,wxapp)
 * @return string 用户 token
 */
function generate_user_token($userId, $deviceType)
{
    $userTokenQuery = Db::name("user_token")
        ->where('user_id', $userId)
        ->where('device_type', $deviceType);
    $findUserToken = $userTokenQuery->find();
    $currentTime = time();
    $expireTime = $currentTime +(getSystem("token")*3600);;
    $token = md5(uniqid()) . md5(uniqid());
    if (empty($findUserToken)) {
        Db::name("user_token")->insert([
            'token' => $token,
            'user_id' => $userId,
            'expire_time' => $expireTime,
            'create_time' => $currentTime,
            'device_type' => $deviceType
        ]);
    } else {
        if ($findUserToken['expire_time'] > time() && !empty($findUserToken['token'])) {
            $token = $findUserToken['token'];
        } else {
            Db::name("user_token")
                ->where('user_id', $userId)
                ->where('device_type', $deviceType)
                ->update([
                    'token' => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }

    }

    return $token;
}

/**
 * 获取系统配置
 * @param $key
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getSystem($key)
{
    $sys = \app\common\model\WebConfigModel::getPublicConfig();

    if (empty($sys[$key])) {
        return false;
    }

    return $sys[$key];
}

/**
 * 获取地区联动
 * @param string $province 省
 * @param string $city 市
 * @param string $area 县
 * @param int $type 类型，不同的样式（备用）
 * @return mixed
 */
function getRegion($type = 0, $province = '', $city = '', $area = '')
{
    $pub = new \app\control\controller\PublicController();

    return $pub->regions($type, $province, $city, $area);
}

/**
 * 获取编辑器
 * @param string $content 内容
 * @param string $name 字段名
 * @param string $height 高度
 * @return string
 */
function getEditor($content = '', $name = 'content', $height = '800')
{
    $pub = new \app\control\controller\PublicController();

    return $pub->ueditor($content, $name, $height);
}

/**
 * 获取后台图片上传插件
 * @param string $content 图片地址
 * @param string $name 字段名
 * @return string
 */
function getUploadImage($url = '', $name = 'thumb', $title = "上传图片")
{
    $pub = new \app\control\controller\PublicController();

    return $pub->uploadImage($url, $name, $title);
}

/**
 * 获取前台图片上传插件
 * @param string $content 图片地址
 * @param string $name 字段名
 * @return string
 */
function getFundImg($url = '', $name = 'thumb', $title = "上传图片")
{
    $pub = new \app\control\controller\PublicController();

    return $pub->getFundImg($url, $name, $title);
}


/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DIRECTORY_SEPARATOR . $item)) {
                        delete_dir_file($dir_name . DIRECTORY_SEPARATOR . $item);
                    } else {
                        unlink($dir_name . DIRECTORY_SEPARATOR . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }
    return $result;
}

/**
 * 错误提示
 * @param string $msg
 * @param string $url
 */
function merror($msg = '错误！', $url = "", $wait = 3)
{
    $result = [
        'code' => 0,
        'msg' => $msg,
        'data' => [],
        'url' => $url,
        'wait' => $wait
    ];

    return $result;
}

/**
 * 生成加密邀请码
 * @param $user_id
 * @return string
 */
function createInviteCode($user_id)
{
    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    $num = $user_id;
    $code = '';

    while ($num > 0) {
        $mod = $num % 35;
        $num = ($num - $mod) / 35;
        $code = $source_string[$mod] . $code;
    }

    if (empty($code[3])) $code = str_pad($code, 4, '0', STR_PAD_LEFT);

    return $code;
}

/**
 * 解密邀请码
 * @param $code
 * @return float|int
 */
function deInviteCode($code)
{
    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);

    $len = strlen($code);
    $code = strrev($code);
    $num = 0;

    for ($i = 0; $i < $len; $i++) {
        $num += strpos($source_string, $code[$i]) * pow(35, $i);
    }

    return $num;
}

/**
 * @param string $tableName 文章名称
 * @param array $titArr 数据表头[一维数组]
 * @param array $data 导出数据[二维数组]
 * @param string $format 格式:excel2003 = xls, excel2007 = xlsx
 * @return bool
 * @throws \PhpOffice\PhpSpreadsheet\Exception
 */
function exportExcel($tableName,$titArr,$data,$format = 'xls')
{
    if(empty($tableName)){
        return false;
    }
    $date = date("Y_m_d", time());
    $tableName=$tableName.'_'.$date;

    $spreadsheet=new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $t = $spreadsheet->setActiveSheetIndex(0);

    // Add title
    $key = ord("A"); // 设置表头
    foreach ($titArr as $val) {
        $colum = chr($key);
        $t->setCellValue($colum . '1', $val);
        $key += 1;
    }

    $sheet = $spreadsheet->getActiveSheet()->setTitle($tableName);

    //Add Data
    $i = 2;
    foreach ($data as $rs) {
        $span = ord("A");
        foreach ($rs as $keyName => $value) { // 列写入
            $j = chr($span);
            $sheet->setCellValue($j . $i, $value);
            $span++;
        }
        $i++;
    }

    $spreadsheet->setActiveSheetIndex(0);

    if (!$spreadsheet) return false;

    if ($format == 'xls') {
        //输出Excel03版本
        header('Content-Type:application/vnd.ms-excel');
        $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
    } elseif ($format == 'xlsx') {
        //输出07Excel版本
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
    }
    //输出名称
    header('Content-Disposition: attachment;filename="' . $tableName . '.' . $format . '"');
    //禁止缓存
    header('Cache-Control: max-age=0');
    $writer = new $class($spreadsheet);
    $filePath = env('runtime_path') . "temp/" . time() . microtime(true) . ".tmp";
    $writer->save($filePath);
    readfile($filePath);
    unlink($filePath);
}

/**
 * 成功返回
 * @param array $data //返回数据
 * @param string $msg //返回信息描述
 * @param int $code //错误码
 * @param int $status // 返回状态：0 失败，1成功
 * @return \think\response\Json
 */
function backSuccess($data=[],$msg="请求成功！",$code=0,$status=1){
    return json([
        'status'=>$status,
        'code'=>$code,
        'msg'=>$msg,
        'data'=>$data,
    ]);
}

/**
 * 成功失败
 * @param string $msg //返回信息描述
 * @param int $code //错误码
 * @param array $data //返回数据
 * @param int $status // 返回状态：0 失败，1成功
 * @return \think\response\Json
 */
function backError($msg="",$code=0,$data=[],$status=0){
    return json([
        'status'=>$status,
        'code'=>$code,
        'msg'=>$msg,
        'data'=>$data,
    ]);
}

/**
 * 号码接口请求
 * @param $url 请求地址
 * @param bool $params 参数
 * @param int $ispost 是否post提交
 * @param bool $curlheader header参数
 * @return bool|mixed
 */
function http_curl($url, $params = false, $ispost = 0,$curlheader=false)
{
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    if($curlheader){
        curl_setopt($ch,CURLOPT_HTTPHEADER,$curlheader);
        curl_setopt($ch, CURLOPT_HEADER, false);//返回response头部信息
    }

    if(1 == strpos("$" . $url, "https://"))
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    }

    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
//    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return json_decode($response,true);
}